package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/longest-palindromic-subsequence/
 */
public class Title516 {

    /**
     * dp[i][j]表示[i...j]中最长的回文子序列长度
     * 递推公式：
     *            if(s.charAt(i) != s.charAt(j)) dp[i][j] = dp[i-1][j-1];
     *                         相等：
     *                                i==j || i==j+1  dp[i][j] = j-1
     *                                i < j
     *                                         dp[i][j] = dp[i+1][j-1] + 2;
     * @param s
     * @return
     */
    public static int longestPalindromeSubseq(String s) {
        int[][] dp = new int[s.length()][s.length()];
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = i; j < s.length(); j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    if (i == j || i + 1 == j) {
                        dp[i][j] = j - i + 1;
                    }else{
                        dp[i][j] = dp[i + 1][j - 1] + 2;
                    }
                }else{
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
                }
            }
        }
        return dp[0][s.length() - 1];
    }


    /**
     * //dp[i][j]表示区间[i,j]最大回文子序列的长度
     *  if(s.charAt(i)== s.charAt(j)) dp[i][j] = dp[i+1][j-1] + 2;
     * @param s
     * @return
     */
    public int longestPalindromeSubseq2(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
                }
            }
        }
        return dp[0][n - 1];
    }

    public static void main(String[] args) {
        longestPalindromeSubseq("bbbab");
    }
}
